<?php

namespace Biz\model\wiki;

use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Doraemon\model\AdmUserType;
use Doraemon\model\Photos;
use Doraemon\service\Comment;
use Medoo\Medoo;

class ObjRelateWiki extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'obj_relate_wiki';

    const OBJ_TYPE_NOTE = 1;//note
    const OBJ_TYPE_BLANK = 2;//文章
    const OBJ_TYPE_ARTICLE = 3;//整屋
    const OBJ_TYPE_GUIDE = 4;//指南
    const OBJ_TYPE_TOPIC = 5;//话题，目前未入库，业务使用

    const OBJ_TYPE_WIKI_ALBUM = 12;//好物清单

    const REL_OBJ_TYPE_PIC = 1;//图片
    const REL_OBJ_TYPE_COMMENT = 2;//评论

    const TYPE_USER_TAG = 1;//通过打标签关联
    const TYPE_WIKI_TO_SPU = 2;//wiki转spu关联
    const TYPE_ARTIFICIAL = 3;//运营人工挂spu
    const TYPE_USER_REL = 4;//用户操作关联
    const TYPE_BRAND_REL = 5;//品牌操作关联

    const STATUS_NORMAL = 1;//已关联
    const STATUS_CLOSE = 0;//取消关联
    const STATUS_DEL = 9;//已删除

    public static $objTypeDesc = [
        self::OBJ_TYPE_NOTE => 'Note',
        self::OBJ_TYPE_BLANK => '文章',
        self::OBJ_TYPE_ARTICLE => '整屋',
        self::OBJ_TYPE_GUIDE => '指南',
    ];

    public static $relObjTypeDesc = [
        self::REL_OBJ_TYPE_PIC => '图片',
        self::REL_OBJ_TYPE_COMMENT => '评论',
    ];

    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date("Y-m-d H:i:s");
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date("Y-m-d H:i:s");
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();
    }

    public static function updateData($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date("Y-m-d H:i:s");
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }

    public static function getByWhere($where, $select = "*")
    {
        return self::select($select, $where);
    }

    public static function getObjIdsByUids(array $uid, $limit)
    {
        $where = [
            'AND' => [
                'uid' => $uid,
                'status' => mObjRelateWiki::STATUS_NORMAL,
                'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK, mObjRelateWiki::OBJ_TYPE_ARTICLE]
            ],
            'LIMIT' => $limit,
            'ORDER' => ['addtime' => 'DESC']
        ];
        $result = self::select(['obj_id' => Medoo::raw("DISTINCT `obj_id`")], $where);
        $result = array_column($result, 'obj_id');
        return $result;
    }

    public static function getObjIdsCountByUids(array $uid)
    {
        $where = [
            'uid' => $uid,
            'status' => mObjRelateWiki::STATUS_NORMAL,
            'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK, mObjRelateWiki::OBJ_TYPE_ARTICLE]
        ];
        $result = self::select(['count' => Medoo::raw("count(DISTINCT `obj_id`)")], $where);
        $count = 0;
        if ($result && $result[0] && isset($result[0]['count'])) {
            $count = $result[0]['count'];
        }
        return $count;
    }

    public static function getCountByWhere($where)
    {
        return self::count($where);
    }

    public static function getWikiRelateCount($wikiId)
    {
        $result = self::select(['count' => Medoo::raw("count(DISTINCT `obj_id`)")], ['wiki_id' => $wikiId, 'status' => self::STATUS_NORMAL]);
        $count = 0;
        if ($result && $result[0] && isset($result[0]['count'])) {
            $count = $result[0]['count'];
        }
        return $count;
    }

    public static function getAllRelateWikIds($objId, $objType, $relObjId, $relObjType)
    {
        $relateWikiIds = self::select('wiki_id', [
            'obj_id' => $objId,
            'obj_type' => $objType,
            'rel_obj_id' => $relObjId,
            'rel_obj_type' => $relObjType,
            'wiki_id[!]' => 0,
            'status' => self::STATUS_NORMAL
        ]);
        return $relateWikiIds;
    }

    public static function getObjIdsByWikiId($wikiId)
    {
        $objIds = self::select('obj_id', [
            'wiki_id' => $wikiId,
            'status' => self::STATUS_NORMAL,
            'ORDER' => ['addtime' => 'DESC']
        ]);
        $objIds = !empty($objIds) ? array_unique($objIds) : [];
        return $objIds;
    }

    public static function getObjIdsByWikiIds($wikiIds)
    {
        $objIds = self::select('obj_id', [
            'wiki_id' => $wikiIds,
            'status' => self::STATUS_NORMAL,
            'ORDER' => ['addtime' => 'DESC']
        ]);
        $objIds = !empty($objIds) ? array_unique($objIds) : [];
        return $objIds;
    }

    // 通过内容id 获取信息列表
    public static function getRelaWikiIdsByObjId($objId)
    {
        $wikiIds = self::select('*', [
            'obj_id' => $objId,
            'status' => self::STATUS_NORMAL,
        ]);

        return $wikiIds;
    }

    public static function getObjIdsByCondition($condition = [])
    {
        $param = [];
        if ($condition['filter_uid']) {
            $param['AND']['uid[!]'] = $condition['filter_uid'];
        }
        if ($condition['uid']) {
            $param['AND']['uid'] = $condition['uid'];
        }
        if ($condition['wiki_id']) {
            $param['AND']['wiki_id'] = $condition['wiki_id'];
        }
        if ($condition['limit']) {
            $param['LIMIT'] = $condition['limit'];
        }
        $param['AND']['status'] = self::STATUS_NORMAL;
        $param['ORDER'] = ['addtime' => 'DESC'];
        $list = self::select('*', $param);
        $uids = array_column($list,'uid');
        $black_uids = AdmUserType::isBlevelMulti($uids);//B级
        $filter_uids = array_merge($black_uids, \Biz\service\wiki\WikiContent::FILTER_UIDS);
        $objIds = [];
        $noteIds = [];
        foreach ($list as $item) {
            $obj_uid = $item['uid'] ?? 0;
            if (in_array($obj_uid, $filter_uids)) {
                continue;
            }else{
                if($item['obj_type'] == self::OBJ_TYPE_NOTE){
                    $noteIds[] = $item['obj_id'];
                }else{
                    $objIds[] = $item['obj_id'];
                }
            }
        }
        if($noteIds){
            $noteInfo = Photos::getPhotos($noteIds,Photos::FINE_GOODS_TEST);
            $noteIds = array_keys($noteInfo);
        }
        return  array_unique(array_merge($objIds,$noteIds));

    }

    /**
     * @param $noteIds
     * @return array|bool
     */
    public static function getTbWikiIdsByNoteIds($noteIds)
    {
        if(empty($noteIds)){
            return [];
        }
        return self::select(['wiki_id', 'obj_id'], [
                'obj_id' => $noteIds,
                'status' => self::STATUS_NORMAL,
            ]) ?? [];
    }

    /**
     * 查询该内容所有绑定的wiki_id(去重)
     *
     * @param $noteId
     * @return array|bool
     */
    public static function getAllWikiIdById($noteId)
    {
        $wikiObjType = Comment::getCommentRelateWikiType($noteId);
        $where = [
            'obj_id' => $noteId,
            'obj_type' => $wikiObjType,
            'status' => mObjRelateWiki::STATUS_NORMAL,
        ];
        $wikiId = mObjRelateWiki::getByWhere($where, 'wiki_id');
        return array_unique($wikiId);
    }
}